package com.lucifer.treasure.enchant.effect;

import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.enchantment.EnchantmentEffectContext;
import net.minecraft.enchantment.EnchantmentLevelBasedValue;
import net.minecraft.enchantment.effect.EnchantmentEntityEffect;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.ItemEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.Hand;
import net.minecraft.util.math.Vec3d;

public record DisarmEnchantmentEffect(EnchantmentLevelBasedValue chance) implements EnchantmentEntityEffect {
    public static final MapCodec<DisarmEnchantmentEffect> CODEC = RecordCodecBuilder.mapCodec(instance ->
            instance.group(
                    EnchantmentLevelBasedValue.CODEC.fieldOf("chance").forGetter(DisarmEnchantmentEffect::chance)
            ).apply(instance, DisarmEnchantmentEffect::new)
    );

    // 配置常量
    private static final double BASE_CHANCE = 0.10; // 10%基础概率
    private static final double CHANCE_PER_LEVEL = 0.05; // 每级增加5%

    @Override
    public void apply(ServerWorld world, int level, EnchantmentEffectContext context, Entity target, Vec3d pos) {
        // 只处理攻击生物的情况
        if (!(target instanceof LivingEntity livingTarget)) {
            return;
        }

        Entity attacker = context.owner();
        if (!(attacker instanceof LivingEntity livingAttacker)) {
            return;
        }

        // 检查是否可以缴械此实体
        if (!canDisarm(livingTarget)) {
            return;
        }

        // 计算缴械概率
        double disarmChance = BASE_CHANCE + (CHANCE_PER_LEVEL * (level - 1));

        if (world.getRandom().nextDouble() > disarmChance) {
            return; // 概率检查失败
        }

        // 尝试缴械主手物品
        boolean disarmedSomething = false;
        if (tryDisarmHand(world, livingTarget, Hand.MAIN_HAND)) {
            disarmedSomething = true;
        }

        // 较低概率同时缴械副手
        if (world.getRandom().nextDouble() < 0.3) { // 30%概率同时缴械副手
            if (tryDisarmHand(world, livingTarget, Hand.OFF_HAND)) {
                disarmedSomething = true;
            }
        }

        // 如果成功缴械，播放效果
        if (disarmedSomething) {
            playDisarmEffects(world, livingTarget);
        }
    }

    /**
     * 尝试缴械指定手的物品
     */
    private boolean tryDisarmHand(ServerWorld world, LivingEntity target, Hand hand) {
        ItemStack heldItem = target.getStackInHand(hand);

        if (heldItem.isEmpty()) {
            return false;
        }

        // 检查是否是不可缴械的物品（如创造模式的工具）
        if (!canDisarmItem(heldItem, target)) {
            return false;
        }

        // 移除目标手中的物品
        target.setStackInHand(hand, ItemStack.EMPTY);

        // 在目标位置掉落物品
        Vec3d targetPos = target.getPos();
        ItemEntity droppedItem = new ItemEntity(
                world,
                targetPos.x,
                targetPos.y + 0.5,
                targetPos.z,
                heldItem
        );

        // 给掉落物品一个小的随机速度
        droppedItem.setVelocity(
                (world.getRandom().nextDouble() - 0.5) * 0.3,
                0.2,
                (world.getRandom().nextDouble() - 0.5) * 0.3
        );

        world.spawnEntity(droppedItem);
        return true;
    }

    /**
     * 检查实体是否可以被缴械
     */
    private boolean canDisarm(LivingEntity target) {
        EntityType<?> entityType = target.getType();

        // 不能缴械的实体类型
        if (entityType == EntityType.ENDER_DRAGON ||
                entityType == EntityType.WITHER ||
                entityType == EntityType.WARDEN) {
            return false;
        }

        // 玩家总是可以被缴械
        if (target instanceof PlayerEntity) {
            return true;
        }

        // 其他生物需要检查是否持有物品
        return !target.getMainHandStack().isEmpty() || !target.getOffHandStack().isEmpty();
    }

    /**
     * 检查物品是否可以被缴械
     */
    private boolean canDisarmItem(ItemStack item, LivingEntity target) {
        // 创造模式玩家的物品不能被缴械
        if (target instanceof PlayerEntity player) {
            if (player.getAbilities().creativeMode) {
                return false;
            }
        }

        // 检查物品是否有特殊的"绑定"标签（如果有的话）
        // 这里可以扩展更多的不可缴械条件

        return true; // 默认所有物品都可以被缴械
    }

    /**
     * 播放缴械特效
     */
    private void playDisarmEffects(ServerWorld world, LivingEntity target) {
        Vec3d targetPos = target.getPos();

        // 播放声音效果
        world.playSound(
                null,
                targetPos.x, targetPos.y, targetPos.z,
                SoundEvents.ITEM_SHIELD_BREAK,
                SoundCategory.PLAYERS,
                0.8f,
                1.2f + world.getRandom().nextFloat() * 0.4f
        );

        // 生成粒子效果
        world.spawnParticles(
                ParticleTypes.SWEEP_ATTACK,
                targetPos.x, targetPos.y + target.getHeight() * 0.7, targetPos.z,
                3, // 粒子数量
                0.3, 0.1, 0.3, // 扩散范围
                0.0 // 初始速度
        );

        // 额外的破碎粒子效果
        world.spawnParticles(
                ParticleTypes.CRIT,
                targetPos.x, targetPos.y + target.getHeight() * 0.5, targetPos.z,
                8, // 粒子数量
                0.2, 0.2, 0.2, // 扩散范围
                0.1 // 初始速度
        );
    }

    @Override
    public MapCodec<? extends EnchantmentEntityEffect> getCodec() {
        return CODEC;
    }
} 